/* 
	封装通用的api 
 */

import $http from "./request.js"
import { api,webUrl } from "./config.js"

export default {
	// 选择图片
	async handleChoose(){
		// 选择图片
		const [err,chooseImageRes] = await uni.chooseImage({
		    count: 1, //默认9
		    sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
		    sourceType: ['album','camera '], //从相册、相机选择
		});
		
		// 获取图片路径
		return await this.handleUpload(chooseImageRes.tempFilePaths[0]);
	},
	// 上传图片
	async handleUpload(tempFilePaths){
		// 上传图片
		let [err1,uploadFileRes] = await uni.uploadFile({
        //#ifdef APP-PLUS
          url: webUrl + api.upload, 
        //#endif
		    //#ifdef H5
		      url: "/" + api.upload, 
		    //#endif
        
		    filePath: tempFilePaths,
		    name: 'image',
		  //   formData: {
				// token: uni.getStorageSync('token')
		  //   }
		});
		
		// 得到服务器返回的图片路径
		const {data}= JSON.parse(uploadFileRes.data)
		
		return data.img_url;
	},
	
	// 图片添加域名
	handleImgUrl: url => url.includes(webUrl) ? url : webUrl + url,
	
	// 封装显示消息提示框。
	showToast: (title,icon='none',position='bottom',mask=true) => uni.showToast({ icon,title,position,mask }),
  
  // 封装跳转
  navigateTo: (url) => uni.navigateTo({url}),
  switchTab: url => uni.switchTab({url}),
  navigateBack: ()=> uni.navigateBack({delta:1}),
  
  // 设置标题
  setNavTitle: title => uni.setNavigationBarTitle({title}),
  
  // 设置tabbar
  setTabBarItem: (index,text) => uni.setTabBarItem({index,text}),
	
	// 验证表单信息
	vali(valiList,self){
		for (let el of valiList) {
			if(typeof el.value !== 'undefined'){   
        
				if(eval(el.rule)){
					this.showToast(el.message);
					return false
				}
			}
			continue;
		}
		return true;
	},
  // 复制文本
  setClipboardData: data=>{
    return new Promise((resolve,reject)=>{
      uni.setClipboardData({
          data,
          success: ()=> {
            console.log('success');
            
              resolve(true)
          },
          fail: ()=>{
            reject(false)
          }
      });
    })
  },
  // 粘贴文本
  getClipboardData: data=>{
    return new Promise((resolve,reject)=>{
      uni.getClipboardData({
          success: (res)=> {
              resolve(res.data)
          },
          fail: ()=>{
            reject(false)
          }
      });
    })
  },
  // 扫描二维码
  scanCode: ()=>{
    return new Promise((resolve,reject)=>{
      uni.scanCode({
          success: function (res) {
            resolve(res)
          }
      });
    })
  },
  // 截屏
  getAppWebview(){
    return new Promise((resolve,reject)=>{ 
      let pages = getCurrentPages();
      let page = pages[pages.length - 1]; 
      let bitmap = null;
      let currentWebview = page.$getAppWebview();
      bitmap = new plus.nativeObj.Bitmap('amway_img');
      // 将webview内容绘制到Bitmap对象中
      currentWebview.draw(
        bitmap,
        function() {
          bitmap.save(
            '_doc/a.jpg',
            {},
            function(i) {
              resolve(i.target)
              bitmap.clear(); //销毁Bitmap图片
            },
            function(e) {
              console.log('保存图片失败：' + JSON.stringify(e));
            }
          );
        },
        function(e) {
          console.log('截屏绘制图片失败：' + JSON.stringify(e));
        }
      );
    })
  },
  // 转换字节
  change(limit){
      var size = "";
      if(limit < 0.1 * 1024){                            //小于0.1KB，则转化成B
          size = limit.toFixed(2) + "B"
      }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB，则转化成KB
          size = (limit/1024).toFixed(2) + "KB"
      }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB，则转化成MB
          size = (limit/(1024 * 1024)).toFixed(2) + "MB"
      }else{                                            //其他转化成GB
          size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB"
      }
  
      var sizeStr = size + "";                        //转成字符串
      var index = sizeStr.indexOf(".");                    //获取小数点处的索引
      var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
      if(dou == "00"){                                //判断后两位是否为00，如果是则删除00
          return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
      }
      return size;
  }
  
}




